/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ipark.gui.mapeditor;

import java.io.*;
import java.util.Vector;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.StreamResult;
import org.jgrapht.graph.SimpleWeightedGraph;
import org.w3c.dom.*;

/**
 * Control object for map editor
 * @author jernej
 */
public class MapControl {
    
    /**
     * load map from file
     * @return saved object
     * @throws java.lang.Exception
     */
    public Vector<WorkArea> loadMapFromFile() throws Exception{
        FileInputStream fis = new FileInputStream("MapData.dat");
        ObjectInputStream in = new ObjectInputStream(fis);
        Vector<WorkArea> readData = null;
        readData = (Vector<WorkArea>)in.readObject();
        in.close();
        return readData;
    }
    
    /**
     * save map to file
     * @param map map to save
     */
    public void saveMapToFile(Vector<WorkArea> map){
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("MapData.dat");
            ObjectOutputStream out = new ObjectOutputStream(fos);
            out.writeObject(map);
            out.close();
            fos.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * method, which save the graph to file, create xml file and add section to database
     * @param graf graph to save
     * @return true if it is successfuly saved, else false
     */
    public boolean saveGraph(SimpleWeightedGraph<MapComponent,RoadEdge> graf){
        FileOutputStream fos;
        try {
            //shranimo serializiran objekt v datoteko
            fos = new FileOutputStream("MapGraph.dat");
            ObjectOutputStream out = new ObjectOutputStream(fos);
            out.writeObject(graf);
            out.close();
            //shranimo sekcije v bazo
            BazaMap baza = new BazaMap();
            baza.writeSections(new Vector<RoadEdge>(graf.edgeSet()));
            //naredimo xml datoteko
            FileWriter fw = new FileWriter("graph.xml");
            fw.write(createXML(graf));
            fw.flush();
            fw.close();
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
    
    /**
     * create xml file from graph
     * @param graf graph to convert to xml
     * @return string, which represents xml file
     * @throws java.lang.Exception
     */
    private String createXML(SimpleWeightedGraph<MapComponent,RoadEdge> graf) throws Exception{
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        DOMImplementation impl = builder.getDOMImplementation();
        Vector<MapComponent> vertexes = new Vector<MapComponent>(graf.vertexSet());
        Vector<RoadEdge> edges = new Vector<RoadEdge>(graf.edgeSet());

        Document doc = impl.createDocument(null,null,null);
        Element e1 = doc.createElement("mapGraph");
        e1.setAttribute("numEdges", Integer.toString(vertexes.size()));
        doc.appendChild(e1);

        //create elements in xml file
        for(int i=0;i<edges.size();i++){
            Element edge = doc.createElement("edge");
            edge.setAttribute("section", edges.get(i).getSection());
            String strDouble = String.format("%.2f m", graf.getEdgeWeight(edges.get(i)));
            edge.setAttribute("length", strDouble);
            edge.setAttribute("numParkBoxes", Integer.toString(edges.get(i).getNumParkBoxes()));
            edge.setAttribute("exitName", edges.get(i).getExitName());
            strDouble = String.format("%.2f m", edges.get(i).getDistanceExit());
            edge.setAttribute("distanceExit", strDouble);
            edge.setAttribute("source", Integer.toString(vertexes.indexOf(graf.getEdgeSource(edges.get(i)))));
            edge.setAttribute("target", Integer.toString(vertexes.indexOf(graf.getEdgeTarget(edges.get(i)))));
            e1.appendChild(edge);
        }

        // transform the Document into a String
        DOMSource domSource = new DOMSource(doc);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        java.io.StringWriter sw = new java.io.StringWriter();
        StreamResult sr = new StreamResult(sw);
        transformer.transform(domSource, sr);
        String xml = sw.toString();
        return xml;
    }

}
